package com.shuiyun.jtt1078.handler.thread;

import com.shuiyun.jtt1078.utils.PropertiesUtil;
import com.shuiyun.jtt1078.utils.SessionManager;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

/**
 * @author shuiyun
 * @program jtt1078
 * @description 推送视频流到RTMP线程 - 守护线程
 * @date 2021-09-08 21:11
 **/
@Slf4j
public class PushVideoThread extends Thread{

    private final String tag;
    Process process = null;

    /** 打开开关的值 */
    private final String switchOn = "on";

    private final boolean saveHistory;
    private final boolean debugMode;

    public PushVideoThread(String tag) {
        this.tag = tag;
        saveHistory = switchOn.equals(PropertiesUtil.get("history.save"));
        debugMode = switchOn.equals(PropertiesUtil.get("debug.mode"));
    }

    @Override
    public void run() {
        InputStream stderr = null;
        int len = -1;
        byte[] buff = new byte[512];

        String rtmpUrl = String.format(PropertiesUtil.get("rtmp.url"),tag);
        String cmd = String.format("%s -i http://localhost:%d/video/%s -vcodec copy -acodec aac -f flv %s",
                PropertiesUtil.get("ffmpeg.path"),
                PropertiesUtil.getInt("server.http.port", 3333),
                tag,
                rtmpUrl
        );
        String saveCmd = String.format("%s -i %s -c copy %s%s.flv ",
                PropertiesUtil.get("ffmpeg.path"),
                rtmpUrl,
                PropertiesUtil.get("history.path"),
                tag
                );



        try {
            log.info("Execute: {}", cmd);
            process = Runtime.getRuntime().exec(cmd);
            if (saveHistory){
                log.info("Execute: {}", saveCmd);
                process = Runtime.getRuntime().exec(saveCmd);
            }
            SessionManager.instance.getProcessMap().put(tag,process);
            log.info("启动推送线程成功-------");
            stderr = process.getErrorStream();
            while ((len = stderr.read(buff)) > -1){
                if (debugMode){
                    System.out.print(new String(buff, 0, len));
                }
            }
        }catch (Exception e){
            log.error("publish failed",e);
        }


    }
}
